import React from "react";
import { FlatList, Picker, Text, View, Alert,  CameraRoll, Image} from "react-native";
import style from './style'

const ITEM_HEIGHT = 100
class Photos extends React.Component {
  static navigationOptions = {
    title: 'photo',
    tabBarLabel: 'photo'
  }
  state = {
    photos: [],
    refrush: false
  }
  componentDidMount() {
    this.has_next_page = true
    this.pageSize = 30
    this.pageNum = 1
    this.getPhotos()
  }
  componentWillUnmount() {
    this.mounted = true
  }
  getPhotos = () => {
    const num = this.pageSize * this.pageNum
    this.pageNum += 1
    CameraRoll.getPhotos({
      first: num
    }).then(res => {
      this.has_next_page = res.page_info.has_next_page
      if(this.mounted){
        return
      }
      this.setState({
        photos: res.edges,
        refrush: false
      })
    })
  }
  _loadMore = () => {
    clearTimeout(this.timeout)
    this.setState({
      refrush: true
    })
    if (this.has_next_page === false) {
      this.timeout = setTimeout(() => {
        if(this.mounted){
          return
        }
        this.setState({
          refrush: false
        })
      }, 1000)
      return
    }
    this.getPhotos()
  }
  _renderItem = ({item}) => (
    <Image
      style={{
        width: '33%',
        height: 100,
        borderColor: '#ffffff',
        borderWidth: 2
      }}
      source={{ uri: item.node.image.uri }}
    />
  )
  _renderFooter = () => {
    return <Text style={style.footer}>{this.has_next_page ? '正在加载中...' : '加载完毕'}</Text>
  }
   
  render() {
    const { photos, refrush } = this.state
    return (
     <View style={{flexDirection: 'column', flex: 1, position: 'relative'}}>
      <View style={style.chooice}>
        <Picker
          style={style.bottom}
          mode='dropdown'
        >
          <Picker.Item label="所有图片" value="java" />
          <Picker.Item label="截图" value="js" />
        </Picker>
      </View>
      <View>
        <FlatList 
          data={photos}
          keyExtractor={(item, index) => item.node.image.uri}
          renderItem={this._renderItem}
          horizontal={false}
          numColumns={3}
          onEndReachedThreshold={2}
          onEndReached={this._loadMore}
          ListFooterComponent={refrush && this._renderFooter}
        />
      </View>
     </View>
    )
  }
}

export default Photos
